const userModel = require('../models/userModel');
const jwt = require('jsonwebtoken');

const login = async (req, res) => {
    try {
        const { username, password } = req.body;
        const user = await userModel.login(username, password);
        if (user) {
            const token = jwt.sign({ id: user.id, username: user.username, isAdmin: user.isAdmin }, 'hrjhrjhrj8', { expiresIn: '1h' });
            res.json({ token });
        } else {
            res.status(401).json({ error: '用户名或密码错误' });
        }
    } catch (error) {
        res.status(500).json({ error: '登录失败' });
    }
};

const register = async (req, res) => {
    try {
        const userId = await userModel.register(req.body);
        res.status(201).json({ id: userId });
    } catch (error) {
        res.status(500).json({ error: '注册失败' });
    }
};

module.exports = {
    login,
    register
};